import os
SCRIPT_DIR = os.path.dirname(os.path.realpath( __file__ ))
PAR2_PATH = os.path.join(SCRIPT_DIR, 'par2')
from shutil import rmtree
from subprocess import Popen, PIPE
from math import ceil
from random import SystemRandom
rand = SystemRandom()

def compute_recovery_file_count(blocks):
	count = 0
	
	i = blocks
	while i > 0:
		count += 1
		i /= 2
		
	return count

def prepare_recovery_volumes(files, par_name, redundancy, block_size = 1280000):
	# redundancy is percentage as an integer
	in_block_count = 0
	for i in files:
		in_block_count += ((os.path.getsize(i) + block_size - 1) / block_size) # + block_size - 1 ensures round up
	
	r_block_count = (in_block_count * redundancy + 50) / 100 # ensure round up
	r_file_count = compute_recovery_file_count(r_block_count)
	par_dir = 'pyencposttemporarypar2folder-%08X' % rand.randint(0, 0xffffffff)
	return {
		'files':			files,
		'par_name':			par_name,
		'block_size':		block_size,
		'in_block_count':	in_block_count,
		'r_block_count':	r_block_count,
		'r_file_count':		r_file_count,
		'par_dir':			par_dir
	}
	
def create_recovery_volumes(files, par_name, block_size, in_block_count, r_block_count, r_file_count, par_dir):
	try:
		os.rmtree(par_dir)
	except:
		pass
	try:
		os.mkdir(par_dir)
	except:
		pass
	arguments = [PAR2_PATH, 'c', '-s%d' % block_size, '-c%d' % r_block_count, '--', os.path.join(par_dir, par_name)]
	arguments += files
	print arguments
	Popen(arguments).communicate()